/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { useState, useRef } from 'react';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    Animated,
} from 'react-native';

import PlaylistHeader from './PlaylistHeader';
import { songs, Track } from '../model';
import CurPlaySong from './CurPlaySong';

import { useBreakpointValue } from '@hadss/react_native_adaptive_layout/src/hooks/useBreakpointValue';
import musicPlayer from '../../util';
// import SampleTurboModule from '../../basic/SampleTurboModule';
import {
    Menu,
    MenuOptions,
    MenuOption,
    MenuTrigger,
    MenuProvider,
} from 'react-native-popup-menu';
import {
    GestureHandlerRootView,
    PanGestureHandler,
    State,
    TapGestureHandler,
} from 'react-native-gesture-handler';
import MusicLove from '../../../../asset/svg/MusicLove';
import SongItemImage from '../../../../asset/svg/SongItemImage'

const { height } = Dimensions.get('window');
const ITEM_HEIGHT = 64; // 每行高度

const SongList = () => {
    const translateY = useRef(new Animated.Value(0)).current;
    const [songsList, setSongsList] = useState(songs);

    const [currentSong, setCurrentSong] = useState<Track>(songs[0]);
    const [isPlaying, setIsPlaying] = useState(false);
    // 单双击事件
    const singleTapRef = React.createRef();

    let itemWidth = useBreakpointValue({
        base: Dimensions.get('window').width - 32,
        sm: Dimensions.get('window').width - 32,
        md: (Dimensions.get('window').width - 72) / 2,
    });

    let itemLeft = useBreakpointValue({
        base: 16,
        sm: 16,
        md: 24,
    });

    // 若是长按时候，阻止单击或双击事件
    const [isLongPressed, setIsLongPressed] = useState(false);
    // 删除数据()
    const deleteItem = (index: number) => {
        setSongsList(songsList =>
            songsList.filter((_item, index1) => index1 !== index),
        );
    };

    // 收藏数据
    const collectItem = (index: number) => {
        setSongsList(songsList =>
            songsList.map((item1, index1) =>
                index1 == index ? { ...item1, hasCollect: true } : item1,
            ),
        );
    };
    // 取消收藏数据
    const deleteCollectItem = (index: number) => {
        setSongsList(songsList =>
            songsList.map((item1, index1) =>
                index1 == index ? { ...item1, hasCollect: false } : item1,
            ),
        );
    };
    const lastOffset = useRef({ y: 0 }).current;
    // 清扫和滚动--start
    const [currentIndex, setCurrentIndex] = useState(0);
    // 保存上一次的轻扫位置数据
    const [targetOffsetNumber, setTargetOffsetNumber] = useState(0);

    const offsetY = useRef(0);

    const onPanGestureEvent = Animated.event(
        [{ nativeEvent: { translationY: translateY } }],
        { useNativeDriver: true },
    );
    const onHandlerStateChange = (event: any) => {
        console.log(22222222)
        const { translationY, velocityY } = event.nativeEvent;
        // 定义轻扫的阈值
        const SWIPE_THRESHOLD1 = 100;
        const VELOCITY_THRESHOLD = 500;
        if (
            Math.abs(translationY) > SWIPE_THRESHOLD1 &&
            Math.abs(velocityY) > VELOCITY_THRESHOLD
        ) {
            const { translationY } = event.nativeEvent;
            // 计算目标索引
            let targetIndex = currentIndex;
            if (translationY < 0) {
                // 向上滑动
                targetIndex = Math.min(currentIndex + 10, songs.length - 9);
            } else if (translationY > 0) {
                // 向下滑动
                targetIndex = Math.max(currentIndex - 10, 0);
            }
            const targetOffset = -targetIndex * ITEM_HEIGHT + lastOffset.y;
            setTargetOffsetNumber(targetOffset);
            // // 动画到目标位置
            Animated.spring(translateY, {
                toValue: targetOffset,
                useNativeDriver: true,
                velocity: event.nativeEvent.velocityY,
            }).start();
            offsetY.current = targetOffset;
            setCurrentIndex(targetIndex);

            translateY.setOffset(targetOffset);
            translateY.setValue(0);
        } else {
            if (event.nativeEvent.oldState === State.ACTIVE) {
                let newOffset =
                    lastOffset.y + targetOffsetNumber + event.nativeEvent.translationY;
                // 设置上边界
                const maxOffset = 0;
                // 设置下边界（根据内容高度计算）
                const minOffset = -((songs.length - 9) * ITEM_HEIGHT);
                let newOffset1 = Math.min(maxOffset, Math.max(minOffset, newOffset));
                lastOffset.y = newOffset1;
                translateY.setOffset(lastOffset.y);
                translateY.setValue(0);
            }
        }
    };
    //列表上的当双击事件---start
    // 记录上次点击时间，用于区分单击和双击
    let lastTap = 0;
    let timerId: any;
    const onHandlerStateChangeForList = (event: any, index: number) => {
        console.log(1111111)
        if (event.nativeEvent.state === State.ACTIVE) {
            const currentTime = Date.now();
            const delta = currentTime - lastTap;
            // 如果两次点击时间差小于300ms，则认为是双击
            if (delta < 300) {
                console.log('Double tap');
                // SampleTurboModule.pushStringToHarmony('pages/MusicPlay', 1);
                musicPlayer.playTrackByIndex(index, true);
                clearTimeout(timerId);
            } else {
                // 否则延迟300ms执行单击事件
                // 这是为了等待可能的第二次点击
                timerId = setTimeout(() => {
                    if (Date.now() - lastTap > 300) {
                        console.log('Single tap');
                        // SampleTurboModule.pushStringToHarmony('pages/MusicPlay', 1);
                        musicPlayer.playTrackByIndex(index, false);
                    }
                }, 300);
            }
            lastTap = currentTime;
        }
    };

    // 在点击列表后面的：的时候，获取点击位置给上下文组件
    const [position, setPosition] = useState({ top: 0, left: 0 });
    const calculateMenuPosition = (event: any) => {
        setPosition({
            top: event.nativeEvent.pageY + 10,
            left: event.nativeEvent.pageX - 50,
        });
    };

    //列表上的当双击事件---end
    const renderItem = (item: Track, index: number) => (
        <GestureHandlerRootView>
            <TapGestureHandler
                ref={singleTapRef}
                onHandlerStateChange={(event: any) =>
                    onHandlerStateChangeForList(event, index)
                }
                numberOfTaps={1}
                enabled={!isLongPressed}>
                <TouchableOpacity
                    style={[styles.songItem, { width: itemWidth, marginLeft: itemLeft }]}>
                    <View style={styles.songInfo}>
                        <View style={{ flexDirection: 'row', top: 2, alignItems: 'center' }}>
                            <Text style={styles.songTitle}>{item.title}</Text>
                            {item.hasCollect ? (
                                <MusicLove style={{ width: 16, height: 14, marginLeft: 10 }} />
                            ) : (
                                ''
                            )}
                        </View>
                        <View style={{ flexDirection: 'row', top: 2 }}>
                            <Image
                                source={require('../../../../asset/acoustic.png')}
                                style={styles.acoustic}
                            />
                            <Text style={styles.songArtist}>{item.artist}</Text>
                        </View>
                    </View>
                    <View style={{ flex: 1 }} />
                    <View
                        style={{ alignItems: 'center', left: -30, marginTop: 20 }}
                        onTouchStart={calculateMenuPosition}>
                        <Menu
                            onClose={() => {
                                setTimeout(() => setIsLongPressed(false), 500);
                            }}>
                            <MenuTrigger
                                triggerOnLongPress={true}
                                onPress={() => {
                                    setIsLongPressed(true);
                                }}>
                                <SongItemImage style={styles.songIcon} />
                                {/* <Image
                                    source={require('../../../../asset/song_item_icon.svg')}
                                    style={styles.songIcon}
                                /> */}
                            </MenuTrigger>
                            <MenuOptions
                                optionsContainerStyle={[
                                    styles.optionList,
                                    {
                                        position: 'absolute',
                                        top: position.top,
                                        left: position.left,
                                    },
                                ]}>
                                <MenuOption onSelect={() => deleteItem(index)}>
                                    <Text>移除</Text>
                                </MenuOption>
                                {item.hasCollect ? (
                                    <MenuOption onSelect={() => deleteCollectItem(index)}>
                                        <Text>移除收藏</Text>
                                    </MenuOption>
                                ) : (
                                    <MenuOption onSelect={() => collectItem(index)}>
                                        <Text>收藏</Text>
                                    </MenuOption>
                                )}
                            </MenuOptions>
                        </Menu>
                    </View>
                </TouchableOpacity>
            </TapGestureHandler>
        </GestureHandlerRootView >
    );
    return (
        <MenuProvider style={{ flex: 1, backgroundColor: 'rgb(239, 239, 239)' }}>
            {/* 列表 , overflow: 'hidden'*/}
            <GestureHandlerRootView style={{ flex: 1 }}>
                <PanGestureHandler
                    onGestureEvent={onPanGestureEvent}
                    onHandlerStateChange={onHandlerStateChange}>
                    <Animated.View style={[{ transform: [{ translateY: translateY }] }]}>
                        <View
                            style={{
                                width: '100%',
                                height: 150,
                            }}>
                            {<PlaylistHeader />}
                        </View>
                        {songsList.map((item, index) => (
                            <View key={index} style={styles.item}>
                                {renderItem(item, index)}
                            </View>
                        ))}
                    </Animated.View>
                </PanGestureHandler>
            </GestureHandlerRootView>
            <CurPlaySong
                song={currentSong}
                setCurrentSong={setCurrentSong}
                isPlaying={isPlaying}
                setIsPlaying={setIsPlaying}
            />
        </MenuProvider>
    );
};

const styles = StyleSheet.create({
    songItem: {
        flexDirection: 'row',
        height: 64,
        alignItems: 'center',
    },
    songInfo: {
        flexDirection: 'column',
        justifyContent: 'center',
    },
    songTitle: {
        fontSize: 16,
        fontWeight: '500',
        lineHeight: 21,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    songArtist: {
        fontSize: 12,
        color: 'rgba(0, 0, 0, 0.4)',
        left: 4,
        lineHeight: 16,
    },
    songIcon: {
        width: 20,
        height: 20,
    },
    acoustic: {
        width: 16,
        height: 16,
    },
    list: {
        paddingBottom: height + ITEM_HEIGHT * 13, // 确保可以滚动到底部
    },
    item: {
        height: ITEM_HEIGHT,
        justifyContent: 'center',
        paddingLeft: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    optionList: {
        width: 120,
        borderRadius: 20,
        paddingVertical: 4,
        paddingHorizontal: 16,
        color: 'rgba(0, 0, 0, 0.9)',
    },
});

export default SongList;
